﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Bitstar.YahooImport;
using Ciripescu_WebRole.BL;
using Ciripescu_WebRole.Entities;
namespace Ciripescu_WebRole
{
    // TODO: trimiterea efectiva a mailurilor din lista send .....poate folosind un azure worker???
    public partial class import : Page
    {
        public string UserName
        {
            get { return (string)Session["UserName"]; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                MailContactList list = (MailContactList)Session["ContactList"];
                gwContacts.DataSource = list;
                gwContacts.DataBind();
            }

        }

        protected void SendEmail()
        {
            MailContactList list = null;
            MailContactList send = new MailContactList();
            InviteManager im = new InviteManager();
            UserManager um = new UserManager();
            User currentUser = um.GetItem((string)Session["UserName"]);
            try
            {

                if (Session["ContactList"] == null)                
                   throw new Exception("Eroare interna. Va rugam incercati mai tarziu");

                list = (MailContactList)Session["ContactList"];                
                

                for (int i = 0; i < gwContacts.Rows.Count; i++)
                {
                    GridViewRow row = gwContacts.Rows[i];
                    bool isChecked = ((CheckBox)row.FindControl("chkMarked")).Checked;

                    if (isChecked)
                    {
                        send.Add(list[i]);
                        ((CheckBox)row.FindControl("chkMarked")).Checked = false;
                    }
                }
                errors.InnerHtml = "Invitatiile au fost trimise! Cand se vor inregistra ei vor fi automat followerii tai!";
                
            }            
            catch (Exception ex)
            {                
                errors.InnerHtml = ex.Message;
                return;
            }
            
            // mailul se pune in codata pt trimitere
            // chiar daca nu e elegant am lasat worker-ul sa mai interogheze tabela invite si sa noteze ca s-a trimit mailul
            // pentru a nu incarca mai tare siteul si a reduce riscul unui timeout
            MailQueue mq = new MailQueue();
            foreach (MailContact mc in send)
                mq.SendInvitation(mc.Name, mc.Email, currentUser.FullName, currentUser.Email);
        }

        protected void Invita_Click(object sender, EventArgs e)
        {
            SendEmail();
        }
    }
}
